package com.example.leetdemo.plan1;

import java.util.ArrayList;
import java.util.List;

public class Sword021 {

    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (head == null) {
            return null;
        }
        ListNode p = head, q = head;
        int l = 0;
        while (p != null) {
            p = p.next;
            l++;
        }
        if (l == n) {
            return head.next;
        }
        int k = 0;
        while (l - n > k + 1) {
            k++;
            q = q.next;
        }
        q.next = q.next.next;
        return head;
    }

    public static void main(String[] args) {
        ListNode listNode = new ListNode(5);
        ListNode listNode1 = new ListNode(4, listNode);
        ListNode listNode2 = new ListNode(3, listNode1);
        ListNode listNode3 = new ListNode(2, listNode2);
        ListNode listNode4 = new ListNode(1, listNode3);
        Sword021 sword021 = new Sword021();
        ListNode head = sword021.removeNthFromEnd(listNode4, 2);
        System.err.println(head.val);
    }
}
